import 'dotenv/config';
import { createHuifengPayService, CreateHuifengPayoutRequest, HuifengPayService } from '../src/services/huifengPayService';

function mask(value: string | undefined): string | undefined {
  if (!value) {
    return value;
  }
  const trimmed = value.trim();
  if (trimmed.length <= 4) {
    return '*'.repeat(trimmed.length);
  }
  return `${'*'.repeat(Math.max(trimmed.length - 4, 0))}${trimmed.slice(-4)}`;
}

function resolveAmount(): number {
  const amountRaw = process.env.HUIFENG_TEST_PAYOUT_AMOUNT ?? '12.11';
  const amount = Number(amountRaw);
  if (!Number.isFinite(amount) || amount <= 0) {
    throw new Error(`无效的测试金额: ${amountRaw}`);
  }
  return amount;
}

function buildPayoutRequest(service: HuifengPayService): CreateHuifengPayoutRequest {
  const amount = resolveAmount();
  const receiverName = process.env.HUIFENG_TEST_RECEIVER_NAME ?? '测试用户';
  const receiverBankCard = process.env.HUIFENG_TEST_RECEIVER_CARD ?? '688899966441';
  const bankCode = process.env.HUIFENG_TEST_BANK_CODE ?? '1122';

  if (!bankCode) {
    throw new Error('缺少银行编码，请设置 HUIFENG_TEST_BANK_CODE');
  }

  const orderId = process.env.HUIFENG_TEST_ORDER_ID ?? service.generateOrderId();
  const accountName = process.env.HUIFENG_TEST_ACCOUNT_NAME ?? receiverName;
  const bankName = process.env.HUIFENG_TEST_BANK_NAME;
  const certificate = process.env.HUIFENG_TEST_CERTIFICATE;
  const subbranch = process.env.HUIFENG_TEST_SUBBRANCH;
  const userIp = process.env.HUIFENG_TEST_USER_IP ?? process.env.HUIFENG_DEFAULT_USER_IP ?? '127.0.0.1';
  const extra = process.env.HUIFENG_TEST_EXTRA;
  const customerEmail = process.env.HUIFENG_TEST_EMAIL ?? process.env.HUIFENG_DEFAULT_EMAIL;
  const customerPhone = process.env.HUIFENG_TEST_PHONE ?? process.env.HUIFENG_DEFAULT_PHONE;
  const remark = process.env.HUIFENG_TEST_REMARK ?? 'Huifeng payout demo';

  const request: CreateHuifengPayoutRequest = {
    amount,
    paymentMethod: 'BankTransfer',
    orderId,
    receiverName,
    receiverBankCard,
    bankCode,
    accountName,
    bankName: bankName?.trim() || undefined,
    certificate: certificate?.trim() || undefined,
    subbranch: subbranch?.trim() || undefined,
    customerEmail: customerEmail?.trim() || undefined,
    customerPhone: customerPhone?.trim() || undefined,
    userIp: userIp?.trim() || undefined,
    extra: extra?.trim() || undefined,
    remark,
  };

  return request;
}

function printInstructions(): void {
  console.log('需要的基础环境变量:');
  console.log('  - HUIFENG_MERCHANT_ID');
  console.log('  - HUIFENG_SECRET_KEY');
  console.log('  - HUIFENG_BASE_URL');
  console.log('  - HUIFENG_NOTIFY_URL');
  console.log('\n可选测试环境变量 (若不设置将使用默认值):');
  console.log('  - HUIFENG_TEST_PAYOUT_AMOUNT (默认 12.11)');
  console.log('  - HUIFENG_TEST_RECEIVER_NAME (默认 "测试用户")');
  console.log('  - HUIFENG_TEST_RECEIVER_CARD (默认 688899966441)');
  console.log('  - HUIFENG_TEST_BANK_CODE (默认 1122)');
  console.log('  - HUIFENG_TEST_ACCOUNT_NAME');
  console.log('  - HUIFENG_TEST_BANK_NAME');
  console.log('  - HUIFENG_TEST_CERTIFICATE');
  console.log('  - HUIFENG_TEST_SUBBRANCH');
  console.log('  - HUIFENG_TEST_EMAIL / HUIFENG_TEST_PHONE');
  console.log('  - HUIFENG_TEST_USER_IP');
  console.log('  - HUIFENG_TEST_EXTRA (需为JSON字符串)');
  console.log('  - HUIFENG_TEST_REMARK');
}

async function main(): Promise<void> {
  console.log('🧪 准备调用汇沣代付 API...');

  try {
    const service = createHuifengPayService();
    const payoutRequest = buildPayoutRequest(service);

    console.log('\n📦 代付请求关键字段预览:');
    console.log('  订单号:', payoutRequest.orderId);
    console.log('  金额(THB):', payoutRequest.amount.toFixed(2));
    console.log('  收款人:', payoutRequest.receiverName);
    console.log('  银行编码:', payoutRequest.bankCode);
    console.log('  银行卡号:', mask(payoutRequest.receiverBankCard));
    console.log('  账户名称:', payoutRequest.accountName);
    console.log('  银行名称:', payoutRequest.bankName ?? '(未提供)');
    console.log('  证件号:', payoutRequest.certificate ? mask(payoutRequest.certificate) : '(未提供)');
    console.log('  支行名称:', payoutRequest.subbranch ?? '(未提供)');
    console.log('  邮箱:', payoutRequest.customerEmail ?? '(未提供)');
    console.log('  手机:', payoutRequest.customerPhone ?? '(未提供)');
    console.log('  用户IP:', payoutRequest.userIp ?? '(未提供)');
    console.log('  扩展字段:', payoutRequest.extra ?? '(未提供)');
    console.log('  备注:', payoutRequest.remark ?? '(未提供)');

    console.log('\n🚀 正在调用 HuifengPayService.createPayoutOrder...\n');
    const response = await service.createPayoutOrder(payoutRequest);

    console.log('✅ 调用成功，返回结果如下:');
    console.log(JSON.stringify(response, (_, value) => (typeof value === 'bigint' ? value.toString() : value), 2));
  } catch (error) {
    console.error('\n❌ 调用失败:');
    if (error instanceof Error) {
      console.error(`  ${error.name}: ${error.message}`);
      if (error.stack) {
        console.error(error.stack);
      }
    } else {
      console.error(error);
    }

    console.log('\nℹ️ 运行提示:');
    printInstructions();
    process.exitCode = 1;
  }
}

void main();
